import { FC } from 'react';
import { Link, LinkProps, useMatch, useResolvedPath } from 'react-router-dom';

type IProps = {
  activeClassName?: string;
} & LinkProps;

const ActiveLink: FC<IProps> = ({
  activeClassName = 'active',
  className,
  children,
  to,
  ...props
}) => {
  const resolved = useResolvedPath(to);
  const match = useMatch({ path: resolved.pathname });

  return (
    <Link
      className={`${className || ''} ${activeClassName && match ? activeClassName : ''}`}
      to={ to }
      { ...props }
    >
      { children }
    </Link>
  );
};

export default ActiveLink;
